/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.controller;

import com.vng.zing.survey.thrift.client.SurveyClient;
import com.vng.zing.survey.thrift.model.ShortInfoSurveyItem;
import com.vng.zing.survey.thrift.model.UserType;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.vng.zing.survey.model.CommonModel.OFFSET;
import com.vng.zing.survey.model.CommonModel;
import java.util.Date;
import java.util.Map;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class AjaxHome extends BaseController {

    private static UserType userType = UserType.USER;

    @Override
    public String render(HttpServletRequest request, HttpServletResponse resp) throws IOException, Exception {

        try {
            if (request.getParameter("page") == null || request.getParameter("type") == null) {
                return CommonModel.toJSON("ERROR", "Tham số không hợp lệ!");
            }
            Integer page = Integer.parseInt(request.getParameter("page"));
            page--;
            Map map = checkMember(request, userType);
            if (map.containsValue(ErrorType.FAIL) || map.containsValue(ErrorType.ERROR_SYSTEM)) {
                return CommonModel.toJSON("ERROR", (String) map.get("msg"));
            }
            int idUser = (int) map.get("msg");
            boolean isAdmin = (boolean) map.get("admin");
            String type = request.getParameter("type");
               int today = (int) (new Date().getTime() / 1000);
            if ("NEW".equals(type)) {
                SurveyClient surveyClient = SurveyClient.getInstance();
                List<ShortInfoSurveyItem> newestSurvey;

                if (isAdmin) {
                    newestSurvey = surveyClient.getListShortInfoSurveyItem(idUser, page, CommonModel.OFFSET, UserType.ADMIN);

                } else {
                    newestSurvey = surveyClient.getListShortInfoSurveyItem(idUser, page, CommonModel.OFFSET, UserType.USER);

                }
                if (request.getParameter("by") != null && request.getParameter("asc") != null) {
                    String by = request.getParameter("by");
                    boolean asc = Boolean.parseBoolean(request.getParameter("asc"));
                    sort(newestSurvey, by, asc);
                }

                TemplateDataDictionary dicNewTable = TemplateDictionary.create();

                for (ShortInfoSurveyItem t : newestSurvey) {
                   TemplateDataDictionary slideItems = dicNewTable.addSection("SLICE_SHOW_ITEMS");
                slideItems.setVariable("RESPONSE_LINK", "response?id=" + t.getIdSurvey());
                slideItems.setVariable("TITLE", t.getTitle());
                slideItems.setVariable("VIEW", String.format("%s", t.getView()));
                slideItems.setVariable("RESPONSE", String.format("%s", t.getResponse()));
                if (isAdmin || t.isOption()) {
                    slideItems.setVariable("LINK", "stat?id=" + t.getIdSurvey());
                } else {
                    slideItems.setVariable("LINK", "#");
                    slideItems.setVariable("DISABLE", "button-zm-dis");
                }
                if (today > t.getEndDay()) {
                    slideItems.setVariable("STATUS", "expired");
                } else if (today < t.getBeginDay()) {
                    slideItems.setVariable("STATUS", "no-active");
                } else {
                    slideItems.setVariable("STATUS", "active");
                }
                }

                return CommonModel.getNewTable(dicNewTable);
            }

            if ("HOT".equals(type)) {
                SurveyClient surveyClient = SurveyClient.getInstance();
                List<ShortInfoSurveyItem> newestSurvey = surveyClient.getListShortInfoSurveyItemHost(idUser, page, OFFSET);
                if (request.getParameter("by") != null && request.getParameter("asc") != null) {
                    String by = request.getParameter("by");
                    boolean asc = Boolean.parseBoolean(request.getParameter("asc"));
                    sort(newestSurvey, by, asc);
                }
                TemplateDataDictionary dicNewTable = TemplateDictionary.create();

                for (ShortInfoSurveyItem t : newestSurvey) {
                   TemplateDataDictionary slideItems = dicNewTable.addSection("SLICE_SHOW_ITEMS");
                slideItems.setVariable("RESPONSE_LINK", "response?id=" + t.getIdSurvey());
                slideItems.setVariable("TITLE", t.getTitle());
                slideItems.setVariable("VIEW", String.format("%s", t.getView()));
                slideItems.setVariable("RESPONSE", String.format("%s", t.getResponse()));
                if (isAdmin || t.isOption()) {
                    slideItems.setVariable("LINK", "stat?id=" + t.getIdSurvey());
                } else {
                    slideItems.setVariable("LINK", "#");
                    slideItems.setVariable("DISABLE", "button-zm-dis");
                }
                if (today > t.getEndDay()) {
                    slideItems.setVariable("STATUS", "expired");
                } else if (today < t.getBeginDay()) {
                    slideItems.setVariable("STATUS", "no-active");
                } else {
                    slideItems.setVariable("STATUS", "active");
                }
                }

                return CommonModel.getHotTable(dicNewTable);
            } else {
                return CommonModel.toJSON("ERROR", " Tham số không hợp lệ!");
            }
        } catch (Exception ex) {
             Logger.getLogger(this.getName()).error(ex.toString());
            return CommonModel.toJSON("ERROR", "");
        }
    }

    private void sort(List<ShortInfoSurveyItem> item, String by, boolean asc) {
        for (int i = 0; i < item.size() - 1; i++) {
            for (int j = i + 1; j < item.size(); j++) {
                if ("VIEW".equals(by)) {
                    if (asc && item.get(i).getView() > item.get(j).getView()) {
                        swap(item, i, j);
                    }
                    if (!asc && item.get(i).getView() < item.get(j).getView()) {
                        swap(item, i, j);
                    }

                }
                if ("RES".equals(by)) {
                    if (asc && item.get(i).getResponse() > item.get(j).getResponse()) {
                        swap(item, i, j);
                    }
                    if (!asc && item.get(i).getResponse() < item.get(j).getResponse()) {
                        swap(item, i, j);
                    }
                }


            }
        }

    }

    void swap(List<ShortInfoSurveyItem> item, int i, int j) {
        ShortInfoSurveyItem temp = item.get(i);
        item.set(i, item.get(j));
        item.set(j, temp);
    }
}
